<template>
  <div class="main" ref="mainRef"></div>
</template>
<script lang="ts">
import { defineComponent, nextTick, onMounted, PropType, ref, watch } from 'vue'
import * as echarts from 'echarts'

// type EChartsOption = echarts.EChartsOption

export default defineComponent({
  name: 'ChartItem',
  props: {
    type: {
      type: String,
      default: 'line',
    },
    color: {
      type: String,
      default: '#006699',
    },
    data: {
      type: Array as PropType<number[]>,
      default: () => [],
    },
    xData: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
  },
  setup(props) {
    const mainRef = ref<HTMLElement>()
    let myChart: any = null

    watch(props, () => {
      nextTick(() => {
        myChart?.setOption(
          getOption(props.xData, props.data, props.type, props.color),
        )
      })
    })
    onMounted(() => {
      if (mainRef.value) {
        myChart = echarts.init(mainRef.value, 'dark')
        myChart.setOption(
          getOption(props.xData, props.data, props.type, props.color),
        )
      }
    })

    return { mainRef }
  },
})

function getOption(xData: any, sData: any, type: any, color: string) {
  const obj: any = {
    backgroundColor: '#21365400',
    color: color,
    xAxis: {
      name: type === 'py' ? '频率' : '时间',
      type: 'category',
      data: xData,
      splitLine: {
        show: true,
      },
      axisLabel: {
        show: true,
        showMaxLabel: true,
        hideOverlap: true,
      },
      axisTick: {
        show: false,
      },
    },
    grid: {
      left: 40,
      top: 20,
      bottom: 20,
      right: 40,
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true,
      },
    },
    series: [
      {
        type: 'line',
        showSymbol: false,
        clip: true,
        data: sData,
        barWidth: 1,
      },
    ],
  }

  if (type === 'xwj') {
    obj.yAxis = {
      type: 'value',
      min: 0,
      max: 180,
      interval: 20,
      splitLine: {
        show: true,
      },
    }
  } else {
    const max = sData.reduce(
        (a: number, b: number) => Math.max(a, b),
        -Infinity,
      ),
      yMax = Math.floor(max / 10) * 10 + 10
    obj.yAxis = {
      type: 'value',
      min: 0,
      max: yMax,
      splitLine: {
        show: true,
      },
    }
  }
  if (type === 'py') {
    obj.series[0].type = 'bar'
    obj.xAxis.axisLabel.interval = 0
    // ;(obj.xAxis.splitLine as any).interval = 1
  }
  return obj
}
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
}
</style>
